<?php

	/**
     * Autolocale
     *
	 * Plugin for language auto detection
	 *
	 * @package      Plugins
	 * @subpackage   Autolocale
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
	 */
    class Plugin_Autolocale implements Core_Plugin_Interface
    {

	////////////////////////////////////////////////////////////////////////////
	//                                Variables                               //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Plugin configuration values
         *
         * @var Zend_Config
         */
        protected $_config = null;

		/**
		 * Zend_Registry object
		 *
		 * @var Zend_Registry
		 */
		protected $_registry = null;

	////////////////////////////////////////////////////////////////////////////
	//                                 Methods                                //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Returns dependencies list.
         *
         * @return      array
         */
        public function getDependencies()
        {
            return array();
        }

        /**
         * Contructor
         *
         * throws       Core_Exception
		 */
        public function __construct()
        {
            $this->_registry = Zend_Registry::getInstance();

            $configuration   = Core_Plugin_Config::getInstance('config.ini.php', $this->_registry['section']);
            $this->_config   = $configuration->{'autolocale'};

            if (!empty($this->_config->requires)) {
                $required = explode(',', $this->_config->requires);

                foreach ($required as $module) {
                    if (!array_key_exists($module, $this->_registry['modules'])) {
                        throw new Core_Exception('Missing plugin dependency: ' . $module);
                    }
                }
            }
        }

		/**
		 * Destructor
		 */
		public function __destruct()
		{
			unset($this);
		}

        /**
         * @param       array       $params : plugin parameters for the current action
         * @return      Core_Selector_Action|null    if action should change
         */
        public function beforeAction($params)
        {
            $lang = '';
            $langDetected = false;
            $availableLang = explode(',', $this->_config->availableLanguages);

            if ($this->_config->detection->url->enable) {
                $coordinator = Core_Controller_Coordinator::getInstance();
                $l = $coordinator->getRequest()->getParam($this->_config->detection->url->param);

                if ($l !== null && !empty($l)) {
                    if (strpos('_', $l) === false) {
                        $lg = strtolower($l) . '_' . strtoupper($l);

                        if (in_array($lg, $availableLang)) {
                            $langDetected = true;
                            $lang = $lg;
                        } else {
                            foreach ($availableLang as $alang) {
                                if (strpos($alang, $l) === 0) {
                                    $lang = $alang;
                                    $langDetected = true;
                                    break;
                                }
                            }
                        }
                    } else if (in_array($l, $availableLang)) {
                        $langDetected = true;
                        $lang = $l;
                    }
                }
            }

			$defaultNamespace = new Zend_Session_Namespace('Default');

            if (!$langDetected) {
                if (isset($defaultNamespace->language)) {
                    $lang = $defaultNamespace->language;
                } else if ($this->_config->detection->browser && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
					$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

                    foreach ($languages as $bl) {
                        // for user-agents with internationnal code
                        if (preg_match("/^([a-zA-Z]{2})(?:[-_]([a-zA-Z]{2}))?(;q=[0-9]\\.[0-9])?$/", $bl, $match)) {
                            $match[1] = strtolower($match[1]);

                            if (isset($match[2])) {
                                $l = $match[1] .'_'. strtoupper($match[2]);
                            } else {
                                $l = $match[1] .'_'. strtoupper($match[1]);
                            }

							if (empty($availableLang)) {
                                $files = Core_IO_Directory::getFiles(Core_IO_Path::combine(
                                                                                           SERUM_MODULE_PATH,
                                                                                           'Core',
                                                                                           'locales',
                                                                                           $this->_registry['end']
                                                                                        ),
                                                                     false
                                                                    );

                                foreach ($files as $file) {
                                    $locale = str_replace('.csv', '', $file);
                                    if (preg_match("/^([a-z]{2})[_]([A-Z]{2})$/", $locale, $match)) {
                                        $availableLang[] = $locale;
                                    }
                                }
                            }

							if (in_array($l, $availableLang)) {
                                $lang = $l;
                                break;
                            } else {
                                // try to find a similary supported language
                                foreach ($availableLang as $alang) {
                                    if (strpos($alang, $match[1]) === 0) {
                                        $lang = $alang;
                                        break;
                                    }
                                }

                                if (!empty($lang)) {
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (!empty($lang)) {
                $defaultNamespace->language = $lang;
                $this->_registry['config']->view->locale = $lang;
            }

            return null;
        }

        public function beforeOutput() { }
        public function afterProcess() { }
    }
